package com.fufu.leetcode;

/**
 * 删除链表的倒数第N个节点
 * @author: BlcakTiger
 * @date: 2023/2/12 16:33
 * @contact: hsf6661@163.com
 */
public class 删除链表的倒数第N个节点No19 {

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        listNode.next = new ListNode(2);
        ListNode res = removeNthFromEnd(listNode,2);
        System.out.println(res);
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        //如果当前节点没有元素或者只有一个元素，直接返回head节点
        if (head==null){
            return head;
        }
        //获取链表长度
        int len = length(head);
        //如果返回的是第一个节点，直接让head节点指向当前head的下一个节点
        if (len==n){
            head = head.next;
            return head;
        }
        //创建辅助节点
        ListNode temp = head;
        for (int i = 1; i <= len-n-1; i++) {
            temp = temp.next;
        }
        temp.next = temp.next.next;
        return head;
    }

    public static int length(ListNode listNode){
        ListNode temp = listNode;
        int count = 0;
        while (temp!=null){
            count++;
            temp = temp.next;
        }
        return count;
    }
}
